package com.lgcns.andteam2.todaymenu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.lgcns.andteam2.todaymenu.db.QueryHelper;
import com.lgcns.andteam2.todaymenu.info.PlaceInfo;
import com.lgcns.andteam2.todaymenu.info.TodayInfo;
import com.lgcns.andteam2.todaymenu.item.TodayMenu;

/**
 * 오늘 메뉴 tab을 보여주는 activity
 */
public class TodayActivity extends ListActivity {
    private static final String TAG = TodayActivity.class.getSimpleName(); 
    
    private String mPlaceId;
    private String mGubunCode;
    private TodayMenuAdapter mAdapter;
    private SimpleDateFormat df = new SimpleDateFormat("M.d(E)");
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(Constants.ACTION_DB_UPDATED.equals(action)) {
                mAdapter.refreshDataSet();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.today);

        mAdapter = new TodayMenuAdapter(this);
        setListAdapter(mAdapter);
        
        ListView list = getListView();
        list.setSelector(new ColorDrawable(0x00000000)); // ListView 선택 안되게
    }
    
    @Override
    protected void onResume() {
        super.onResume();

        String gubunCode = TodayInfo.getTodayInfo(this).getGubunCode();
        
        // 새로 실행되었거나, 사업장 설정정보가 변경된 경우 새로 조회
        String placeId = PlaceInfo.getInstance(this).getPlaceId();
        if(mPlaceId == null || !mPlaceId.equals(placeId)) {
            mPlaceId = placeId;
            mAdapter.refreshDataSet();
            mGubunCode = gubunCode;  
        } else if(mGubunCode != null && !mGubunCode.equals(gubunCode)) {
            // 이전에 이미 실행된 상태였고, onResume()되는 시점에 gubunCode가 바뀐(식사 시간이 변경된) 경우 새로 조회
            mAdapter.refreshDataSet();
            mGubunCode = gubunCode;  
        }
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_DB_UPDATED);
        registerReceiver(mReceiver, filter);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    }
    
    /**
     * 오늘 메뉴 데이터&View를 가지는 adapter
     */
    private class TodayMenuAdapter extends BaseAdapter {
        private Context context;
        private ArrayList<TodayMenu> mMenuList;
        private LayoutInflater inflater;

        public TodayMenuAdapter(Context context) {
            super();
            this.context = context;
            mMenuList = new ArrayList<TodayMenu>(); // adapter 생성시에는 빈 데이터 생성
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        /**
         * Adapter의 데이터를 query한다.
         */
        private void queryData() {
            QueryHelper.populateTodayMenuData(context, mMenuList);
        }
        
        @Override
        public int getCount() {
            return mMenuList.size();
        }

        @Override
        public Object getItem(int position) {
            return mMenuList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
            if(convertView == null) {
                convertView = inflater.inflate(R.layout.today_row, parent, false);
            }
            
            TextView corner = (TextView)convertView.findViewById(R.id.corner);
            TextView menuName = (TextView)convertView.findViewById(R.id.menu_name);
            TextView cal = (TextView)convertView.findViewById(R.id.cal);
            TextView sideMenu = (TextView)convertView.findViewById(R.id.side_menu);
            Button survey = (Button)convertView.findViewById(R.id.survey);
            
            TodayMenu menu = mMenuList.get(position);
            if(!TextUtils.isEmpty(menu.getCorner())) {
                corner.setVisibility(View.VISIBLE);
                corner.setText(menu.getCorner());
            } else {
                corner.setVisibility(View.GONE);
            }
            
            menuName.setText(menu.getMenuName());
            cal.setText(String.format(getString(R.string.cal), Util.formatNumber(menu.getCal())) + " "); // " "은 italic체로 할 경우 맨 끝 문자가 약간 잘리는 것 방지
            sideMenu.setText(menu.getSideMenuList(getApplicationContext()));
            
            final int sPlaceId = menu.getPlaceId();
            
            StringBuffer tmp = new StringBuffer();
            tmp.append(getString(R.string.survey)).append(": ");
            tmp.append(df.format(Util.parseCalendar(menu.getMenuDate()).getTime())).append(" - ");
            if(!TextUtils.isEmpty(menu.getCorner())) {
                tmp.append(menu.getCorner()).append("/");
            }
            tmp.append(menu.getMenuName());
            final String subject = tmp.toString();
            
            survey.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 담당자에게 설문 보내기
                    String[] email = QueryHelper.getDietitianEmail(TodayActivity.this, sPlaceId);
                    
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/html");
                    intent.putExtra(Intent.EXTRA_EMAIL, email);
                    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
                    intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.survey_opinion));
                    startActivity(intent);
                }
            });
            
            return convertView;
        }
        
        /**
         * Adapter의 데이터를 갱신한다.
         */
        public void refreshDataSet() {
            queryData();
            notifyDataSetChanged();
        }
    }
}
